package com.happy.ibidding.service;

import com.happy.ibidding.bean.Ask;
import com.happy.ibidding.bean.Bid;
import com.happy.ibidding.dao.AskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AskService {

    final private AskRepository askRepository;

    @Autowired
    public AskService(AskRepository askRepository) {
        this.askRepository = askRepository;
    }

    public Ask save(Ask ask) {
        return this.askRepository.save(ask);
    }

    public Ask changeState(String askId, String state) {
        Ask ask = this.view(askId);
        ask.setState(state);
        return this.save(ask);
    }

    public List<Ask> viewAll() {
        return this.askRepository.findAll();
    }

    public Ask view(String askId) {
        Ask ask= this.askRepository.findByAskId(askId);

        if(Objects.nonNull(ask.getBidList())) {
            List<Bid> winBidList = ask.getBidList().parallelStream().filter(Bid::isWin).collect(Collectors.toList());
            if (winBidList.size() > 0) {
                ask.setWinBid(winBidList.get(0));
            }
        }

        return ask;
    }

}
